import { getRandomKey, setRandomKey, mobile } from "@/utils/tools"
import instance from "@/pinia"
import { usePageRefresh, useEventSource, useElMessageBox, useElMessage, useRequest } from "@usehook"
import { baseUrl } from "@/utils/constant"

const getClientId = () => {
    let clientId = getRandomKey()
    if (!clientId) clientId = setRandomKey()
    return clientId
}

const clientId = $computed(() => {
    const sequence = instance.userStore?.getUserInfo.sequence
    return getClientId() + (sequence ? "@" + sequence : "")
})

let lastEventId = $ref("")
let sseSource = $ref(null)
const sseConnectStatus = ref(false)

export const startSSE = () => {
    if (mobile) return sseConnectStatus
    watch(() => clientId, (newVal, oldVal) => {
        if (sseSource) sseSource.close()
        if (oldVal) useRequest.post({ url: "/sse/removeClient", clientId: oldVal })
        sseSource = useEventSource(baseUrl + "/sse/connect?clientId=" + newVal, ["update", "notice"], {
            autoReconnect: {
                retries: 6,
                delay: 10000,
                onFailed() {
                    console.log('failed to connect eventSource after 3 retries')
                },
            }
        })
    }, { immediate: true })

    watch(() => sseSource, (newVal) => {
        sseConnectStatus.value = newVal.status === "OPEN"
        if (newVal && newVal.data && lastEventId !== newVal.lastEventId) {
            lastEventId = newVal.lastEventId
            if (newVal.event === "notice") {
                const message = JSON.parse(newVal.data)
                if (message.messageType === 3) {
                    useElMessageBox.info(message.content ? message.title : "Message", message.content ? message.content : message.title)
                } else {
                    useElMessage.info({
                        notice: message.messageType === 2,
                        dangerouslyUseHTMLString: true,
                        message: message.content,
                        title: message.title,
                        duration: 0
                    })
                }
            } else if (newVal.event === "update") {
                const beforeClose = (action, instance, done) => {
                    if (action === 'confirm') {
                        instance.confirmButtonLoading = true
                        setTimeout(() => {
                            done()
                            instance.confirmButtonLoading = false
                        }, 500)
                    } else {
                        done()
                    }
                }
                useElMessageBox("发现新版本", "立即更新至新版本?", { showCancelButton: true, falseInCatch: true, beforeClose }).then(() => { location.reload() }).catch(() => { })
            }
        }
    }, { deep: true })
    return sseConnectStatus
}


usePageRefresh(() => {
    useRequest.post({ url: "/sse/removeClient", clientId: clientId })
})